#!/bin/bash
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/sys_check.sh"
export GLOBAL_TOOLS_DIR="${LMD_DATA_ROOT}/scripts/global-tools"
export MINICONDA_INSTALL_TARGET_DIR_WIN="${GLOBAL_TOOLS_DIR}/miniconda3"

function check_miniconda_dir {
    MINICONDA_DIR_IN_HOME="${HOME}/miniconda3"
    export MINICONDA_DIR="$MINICONDA_DIR_IN_HOME"
    
    if current_os_is_windows; then
        # Windows
        CONDA_BIN_PATH=$(command -v "${MINICONDA_INSTALL_TARGET_DIR_WIN}/Scripts/conda")        
        if [ -z "$CONDA_BIN_PATH" ]; then
            CONDA_BIN_PATH=$(command -v "${MINICONDA_DIR_IN_HOME}/Scripts/conda")
            if [ -z "$CONDA_BIN_PATH" ]; then
                echo "check conda in HOME dir: $CONDA_BIN_PATH"
                MINICONDA_DIR_IN_PROGRAM_DATA="/c/ProgramData/miniconda3"
                export MINICONDA_DIR="$MINICONDA_DIR_IN_PROGRAM_DATA"
            fi
        else
            MINICONDA_INSTALL_TARGET_DIR_WIN=$(echo "$MINICONDA_INSTALL_TARGET_DIR_WIN" | tr '\\' '/')
            export MINICONDA_DIR="${MINICONDA_INSTALL_TARGET_DIR_WIN}"
            echo "Found conda in LMD global-tools: $MINICONDA_DIR"
        fi
    fi
}

check_miniconda_dir

echo "MINICONDA_DIR: $MINICONDA_DIR"

convert_path() {
    local win_path="$1"

    # 1. Replace backslashes with forward slashes.
    local linux_path="${win_path//\\//}"

    # 2. Convert the drive letters in the Windows system to lowercase. C: -> /c
    if [[ $linux_path =~ ^[A-Za-z]: ]]; then
        local drive_letter=$(echo "$linux_path" | cut -c1 | tr '[:upper:]' '[:lower:]')
        local rest_path=$(echo "$linux_path" | cut -c3-)
        linux_path="/$drive_letter/$rest_path"
    fi

    # 3. clear duplicated "/".
    linux_path=$(echo "$linux_path" | sed 's|//|/|g')

    echo "$linux_path"
}

function set_default_alias {
    # create alias
    if [ -f /System/Library/CoreServices/SystemVersion.plist ]; then
        # echo "macOS system."
        alias python="$MINICONDA_DIR/bin/python"
        alias python3="$MINICONDA_DIR/bin/python3"
        alias conda="$MINICONDA_DIR/bin/conda"
        alias pip="$MINICONDA_DIR/bin/pip3"
        alias pip3="$MINICONDA_DIR/bin/pip3"
    elif current_os_is_windows; then
        # echo "Windows system."
        MINICONDA_DIR=$(convert_path "$MINICONDA_DIR")
        echo "MINICONDA_DIR converted: $MINICONDA_DIR"
        alias python="$MINICONDA_DIR/python"
        alias python3="$MINICONDA_DIR/python"
        alias conda="$MINICONDA_DIR/Scripts/conda"
        alias pip="$MINICONDA_DIR/Scripts/pip3"
        alias pip3="$MINICONDA_DIR/Scripts/pip3"
        # add ffmpeg dir to PATH
        ffmpeg_path=$(convert_path "${GLOBAL_TOOLS_DIR}/ffmpeg/")
        export PATH=$PATH:$ffmpeg_path
    fi

}

set_default_alias

python --version
conda --version
pip --version
